package top.anydata.lifeofcode.lifesystem.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.anydata.lifeofcode.lifesystem.conf.global.exception.DecryptException;

/**
 * 功能描述:
 *
 * @author <a href="mailto:caingao@anydata.top">CainGao</a>
 * @version V_1.0
 * @date 2023/5/15 8:51 PM
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResult handleException(Exception e) {
        if (e instanceof IllegalArgumentException){
            log.debug("e",e);
            return new BaseResult().error(RestResultEnum.USER_IN_USED);
        }
        if(e instanceof UsernameNotFoundException){
            log.debug("e",e);
            return new BaseResult().error(RestResultEnum.USER_NOF_FOUND);
        }
        if(e instanceof AccessDeniedException){
            log.debug("e",e);
            return new BaseResult().error(RestResultEnum.USER_ACCESS_DENIED);
        }
        if(e instanceof MethodArgumentNotValidException){
            log.debug("e",e);
            return new BaseResult().error(RestResultEnum.ERROR_DATA);
        }
        if(e instanceof DecryptException){
            log.debug("e",e);
            return new BaseResult().error(RestResultEnum.ERROR_DECRYPT);
        }
        log.warn("GlobalExceptionHandler捕获到异常", e);
        // 处理异常并返回统一格式的错误信息
        return new BaseResult().error(RestResultEnum.ERROR_SYS);
    }
}
